package com.muyu.chat.websocket;

import com.alibaba.fastjson2.JSONObject;
import com.muyu.chat.doamin.SendMessage;
import com.muyu.chat.websocket.server.ChatSessionLocalLocalOnline;
import com.muyu.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.*;


/**
 * 聊天服务 在线人数
 *
 * */
@Slf4j
@ServerEndpoint("/websocket/{uid}")
@Component
public class WebSocketServer {

    /**
     * 聊天socket存储对象
     */
    private ChatSessionLocalLocalOnline sessionLocal;

    public WebSocketServer() {
        this.sessionLocal = ChatSessionLocalLocalOnline.getInstance();
    }

    /**
     * 连接
     * @param session
     * @param uid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("uid") Long uid) {
        log.info("New connection: " + uid);
        sessionLocal.storage(session, uid);
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(Session session) {
        sessionLocal.destroyBySession(session);
    }



    /**
     * 发送消息
     * @throws IOException
     */
    @OnMessage
    public void send(Session session,@PathParam("uid") Long userId, String sendMessageStr) throws IOException {
        SendMessage sendMessage = null;
        try {
            sendMessage = JSONObject.parseObject(sendMessageStr, SendMessage.class);
        }catch (Exception exception){
            String errorMsg = StringUtils.format(
                    "JSON解析异常：{}", sendMessageStr
            );
            log.error(errorMsg);
            sessionLocal.sendBySession(session, errorMsg);
            return;
        }
        if (sendMessage.getMessage()==null || sendMessage.getMessage().equals("")){
            session.getBasicRemote().sendText("{\"status\": \"error\", \"message\": \"消息不能为空\"}");
            return;
        }
        if (sessionLocal.isOnlineByUserId(sendMessage.getReceiveId())) {

            sessionLocal.sendByUserId(sendMessage.getReceiveId(),sendMessage.getMessage());
            log.info("用户：{} 向用户： {} 发送了信息：{}", session.getId(), sendMessage.getReceiveId(), sendMessage.getMessage());
            session.getBasicRemote().sendText("{\"status\": \"success\", \"message\": \"消息已送达\"}");

            // 这里可以通过 WebSocket 将消息推送到前端
            String pushMessage = "{\"status\": \"newMessage\", \"message\": \"" + sendMessage.getMessage() + "\"}";
            sessionLocal.sendBySession(session, pushMessage);  // 这里假设 sessionLocal.sendBySession() 可以推送给客户端

        } else {
            log.info("用户：{} 没在线", sendMessage.getReceiveId());
            // 保存离线消息
            saveOfflineMessage(userId, userId,sendMessage.getReceiveId(), sendMessage.getMessage(), sendMessage.getType());
            // 发送离线提示给前端
            session.getBasicRemote().sendText("{\"status\": \"offline\", \"message\": \"接收方不在线，消息已保存\"}");
        }

    }

    private static final String URL = "jdbc:mysql://20f78265-fd98-4840-8d92-e6605ec424f8:3306/shuhua_cloud";
    private static final String USER = "root";
    private static final String PASSWORD = "WangShuhua820!";

    public void saveOfflineMessage(Long uid,Long sender, Long acceptor, String content, String type) {
        String sql = "INSERT INTO chat_message (send_user_id, accept_user_id, content, send_time,type,identification) VALUES (?, ?, ?, ?,?,?)";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setLong(1, sender);
            pstmt.setLong(2, acceptor);

            pstmt.setObject(3,content );
            pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
            pstmt.setString(5, "txt");
            int identification = 0; // 默认值
            if (sender != null && sender.equals(uid)) {
                identification = 1; // 如果发送者是当前用户，设置为1
            } else {
                identification = 2; // 如果发送者不是当前用户，设置为2
            }
            pstmt.setLong(6, identification);
            pstmt.executeUpdate();
            log.info("离线消息已保存：{} -> {}", sender, acceptor);
            log.info("离线消息已保存：{}", content);
        } catch (SQLException e) {
            log.error("保存离线消息失败", e);
            e.printStackTrace();
        }
    }

}





